<template>
  <el-container class="home-container">
    <!-- 头部区域 -->
    <el-header>
      <div>
        <img src="../assets/navLogo.png" alt="" />
        <span>仓库管理系统</span>
      </div>
      <div>
        <div class="login-time">{{ time }}</div>
        <el-button type="info" @click="lock">锁屏</el-button>
        <el-tooltip :content="'当前用户：' + user" placement="top">
          <el-button type="info" @click="modifyPswDialog = true"
            >修改密码</el-button
          >
        </el-tooltip>
        <el-tooltip :content="'当前用户：' + user" placement="top">
          <el-button type="info" @click="logout">退出</el-button>
        </el-tooltip>
      </div>
    </el-header>
    <!-- 主体区域 -->
    <el-container>
      <!-- 侧边栏 ,根据折叠与否决定侧边栏的宽度-->
      <el-aside :width="isCollpse ? '64px' : '200px'">
        <!-- 菜单栏折叠和展开 -->
        <div class="toggle-button" @click="toggleCollapse">| | |</div>
        <!-- 侧边栏菜单区域 -->
        <el-menu
          background-color="#21252b"
          text-color="#fff"
          active-text-color="#409eff"
          unique-opened
          :collapse="isCollpse"
          :collapse-transition="false"
          router
          :default-active="activePath"
        >
          <!-- 一级菜单 -->
          <el-submenu
            :index="item.id + ''"
            v-for="item in menulist"
            :key="item.id"
          >
            <!-- 一级菜单的模板区 -->
            <template slot="title">
              <!-- 图标 -->
              <i :class="iconsObj[item.id]"></i>
              <!-- 文本 -->
              <span>{{ item.title }}</span>
            </template>
            <!-- 二级菜单 -->
            <el-menu-item
              :index="subItem.path"
              v-for="subItem in item.sList"
              :key="subItem.id"
              @click="saveNavState(subItem.path)"
            >
              <template slot="title">
                <!-- 图标 -->
                <i :class="iconsObj[subItem.id]"></i>
                <!-- 文本 -->
                <span>{{ subItem.title }}</span>
              </template>
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>
      <!-- 右侧内容 -->
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
    <el-dialog
      title="修改密码"
      :visible.sync="modifyPswDialog"
      width="50%"
      @close="modifyPswClose"
    >
      <el-form
        ref="modifyForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass"></el-input>
        </el-form-item>
        <el-form-item label="输入新密码" prop="newPass">
          <el-input type="password" v-model="ruleForm.newPass"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyPswDialog = false">取 消</el-button>
        <el-button type="primary" @click="modifyPsw">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import { dateFormat } from '@/util/date.js'
export default {
  data() {
    return {
      // 左侧菜单数据
      menulist: [],
      // 动态添加图标
      iconsObj: {
        100: 'el-icon-user',
        101: 'el-icon-user-solid',
        200: 'el-icon-box',
        201: 'el-icon-box',
        202: 'el-icon-shopping-bag-1',
        300: 'el-icon-goods',
        301: 'el-icon-document',
        302: 'el-icon-shopping-cart-full',
        400: 'el-icon-s-order',
        401: 'el-icon-notebook-1',
        402: 'el-icon-coin',
        500: 'el-icon-s-custom',
        501: 'el-icon-fork-spoon',
        502: 'el-icon-dish-1',
        600: 'el-icon-s-data',
        601: 'el-icon-data-analysis',
        602: 'el-icon-data-analysis'
      },
      //时间
      time: '',
      // 是否折叠
      isCollpse: false,
      // 被激活的链接地址
      activePath: '',
      user: '',
      isLock: false,
      //修改密码弹窗
      modifyPswDialog: false,
      ruleForm: {
        pass: '',
        checkPass: '',
        newPass: ''
      },
      rules: {
        pass: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        checkPass: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        newPass: [
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getTime()
    this.getMenuList()
    this.activePath = window.sessionStorage.getItem('activePath')
    this.user = window.sessionStorage.getItem('user')
  },
  methods: {
    getTime() {
      setInterval(() => {
        this.time = dateFormat(new Date())
      }, 1000)
    },
    lock() {
      console.log('锁屏')
      const that = this
      that
        .$prompt('请输入锁屏密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S/, //判断不为空正则
          inputErrorMessage: '锁屏密码不能为空'
        })
        .then(({ value }) => {
          that.isLock = !that.isLock
          console.log('value', value)
          that.$store.commit('SET_LOCK_PASSWD', value)
          that.$message.success('锁屏成功')
          this.handleLock()
        })
        .catch(() => {
          that.$message.error('锁屏失败')
        })
    },
    handleLock() {
      console.log('lock!!')
      this.$store.commit('SET_LOCK')
      setTimeout(() => {
        this.$router.push('/lock')
      }, 100)
    },
    logout() {
      //清除session，回到登录页
      window.sessionStorage.clear()
      this.$router.push('/login')
    },
    modifyPsw() {
      console.log('openmodify')
      this.$refs.modifyForm.validate(async valid => {
        if (!valid) return false
        if (this.ruleForm.pass != this.ruleForm.checkPass) {
          return this.$message.error('两次输入密码不一样!')
        }
        if (this.ruleForm.pass != this.$store.state.loginPsw) {
          return this.$message.error('输入密码有误!')
        }
        //验证通过发起的网络请求
        const { data: res } = await this.$http.put(
          `modifyPsw?newPsw=${this.ruleForm.newPass}&user=${this.user}`
        )
        if (res !== 'success') {
          return this.$message.error('修改密码失败')
        }
        this.$message.success('修改密码成功')
        // 隐藏添加用户对话框
        this.modifyPswDialog = false
      })
    },
    // 监听对话框的关闭事件
    modifyPswClose() {
      this.$refs.modifyForm.resetFields()
    },
    // 网络请求获取所有菜单
    async getMenuList() {
      const { data: res } = await this.$http.get('menus')
      console.log(res)
      if (res.status !== 200) return this.$message.error(res.msg)
      this.menulist = res.menus
    },
    // 点击按钮切换菜单折叠
    toggleCollapse() {
      this.isCollpse = !this.isCollpse
    },
    // 保存链接的激活状态
    saveNavState(activePath) {
      window.sessionStorage.setItem('activePath', activePath)
      this.activePath = activePath
    }
  }
}
</script>

<style lang="less" scoped>
.home-container {
  height: 100%;
}

.el-header {
  background: linear-gradient(120deg, #1a2024, #5b6a72);
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  font-size: 20px;
  > div {
    display: flex;
    align-items: center;
    span {
      margin-left: 20px;
    }
  }
}

.el-aside {
  background-color: #21252b;
  .el-menu {
    border-right: none;
  }
}

.el-main {
  background-color: #eaedf1;
}

.toggle-button {
  background-color: #53575f;
  font-size: 10px;
  line-height: 24px;
  color: #fff;
  text-align: center;
  letter-spacing: 0.2em;
  cursor: pointer;
}
.login-time {
  margin-right: 20px;
  text-align: center;
  width: 100%;
  color: #fff;
  font-weight: 200;
  opacity: 0.7;
  font-size: 18px;
  overflow: hidden;
}
</style>
